package hello

import (
	"appengine"
	"appengine/datastore"
)

type Product struct {
	Name string
	Id int64
}

func createProductKey(c *appengine.Context) (key *datastore.Key) {
	key = datastore.NewIncompleteKey(*c, "Product", nil)
	return
}

func restoreProductKey(c *appengine.Context, id int64) (key *datastore.Key) {
	key = datastore.NewKey(*c, "Product", "", id, nil)
	return
}

func listAllProducts(c *appengine.Context) []*Product {
	q := datastore.NewQuery("Product").Order("Name")
	products := make([]*Product, 0)
	_, err := q.GetAll(*c, &products)
	panicIfErr(err)
	return products
}

func saveProduct(c *appengine.Context, product *Product) (key *datastore.Key, err error) {
	key, err = datastore.Put(*c, createProductKey(c), product)
	panicIfErr(err)
	product.Id = key.IntID()
	key, err = datastore.Put(*c, key, product)
	panicIfErr(err)
	return
}

func getProduct(c *appengine.Context, id int64) (product *Product, err error) {
	product = new(Product)
	err = datastore.Get(*c, restoreProductKey(c, id), product)
	return
}

func updateProduct(c *appengine.Context, id int64, product *Product) (key *datastore.Key, err error) {
	// update dependend ingredients
	ingredients := make([]*Ingredient, 0)
	_, err = datastore.NewQuery("Ingredient").Filter("ProductId =", id).GetAll(*c, &ingredients)
	for i := 0; i < len(ingredients); i++ {
		ingredient := ingredients[i]
		ingredient.Name = product.Name
		updateIngredient(c, ingredient.Id, ingredient)
	}
	panicIfErr(err)
	
	product.Id = id
	key, err = datastore.Put(*c, restoreProductKey(c, id), product)
	return
}

func deleteProduct(c *appengine.Context, id int64) error {
	return datastore.Delete(*c, restoreProductKey(c, id))
}
